import { routerRedux } from 'dva/router';
import {
    getCostTrend, CostCalender, getCostReport
} from '../services/costService';
import moment from 'moment';

const initialState = {
    
    currentPage:1,
    total:0,
    isLoading:false,
    // 1成本 5能耗
    dataType:1,
    costData:[],
    costTrend:{}
};

export default {
    namespace: 'cost',
    state: initialState,
    effects: {
        *fetchCostReport(action, { call, put, select }){
            let { user:{ companyId, startDate, endDate, timeType }, fields:{ currentAttr }, cost:{ dataType }} = yield select();
            let { resolve, reject, currentPage, pageSize } = action.payload || {};
            currentPage = currentPage || 1;
            pageSize = pageSize || 12;
            timeType = timeType === '10' ? '2' : timeType;
            yield put({ type:'toggleLoading'});
            let { data, code, message, total } = yield call(getCostReport, { companyId, typeId:dataType, attrId:currentAttr.attrId, beginDate:startDate.format('YYYY-MM-DD'), endDate:endDate.format('YYYY-MM-DD'), timeType, page:currentPage, pageSize });
            if ( code === 200 ) {
                if ( resolve ) {
                    resolve(data);
                    yield put({ type:'closeLoading' });
                } else {
                    yield put({ type:'getCostReportResult', payload:{ data, currentPage, total }});
                }
            } else {
                if ( reject ) reject(message);
            }
        },
        *fetchCostTrend(action, { call, put, select }){
            let { user:{ companyId, startDate, endDate, timeType }, fields:{ currentEnergy }} = yield select();
            yield put({ type:'toggleLoading'});
            timeType = timeType === '10' ? '2' : timeType;
            
            let { data, code, message } = yield call(getCostTrend, { companyId, energyType:currentEnergy, timeType, beginDate:startDate.format('YYYY-MM-DD'), endDate:endDate.format('YYYY-MM-DD')});
            if ( code === 200 ) {
                yield put({ type:'getCostTrendResult', payload:{ data }});
            }
        }
        
    },
    reducers: {
        toggleLoading(state){
            return { ...state, isLoading:true };
        },
        closeLoading(state){
            return { ...state, isLoading:false };
        },
        getCostReportResult(state, { payload:{ data, total, currentPage }}){
            return { ...state, costData:data, total, currentPage, isLoading:false };
        },
        getCostTrendResult(state, { payload:{ data }}){
            return { ...state, costTrend:data, isLoading:false };
        },
        
        
    }
};
